//
//  CollectionViewModel.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/12.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import RxDataSources

class CollectionViewModel: LSFRefreshProtocol {
    var disposeBag = DisposeBag()
    
    public let vmDatas = Variable([CollectionSection]())
    
    ///刷新状态
    var refreshStatus = Variable<LSFRefreshStatus>(.none)
    
    ///是否是空数据
    var isNull = Variable<Bool>(false)
    
    /// 发送请求，参数：是否是下拉刷新
    var requestCommand = PublishSubject<Bool>()
    
    init() {
        self.requestCommand.subscribe(onNext: { [weak self] (isPull) in
            self?.getCollectionList()
        }).disposed(by: disposeBag)
    }
    
    func getCollectionList() {
        paperProvider.rx.request(.likesList).asObservable().mapRespnseToObjectArray(type: CollectionModel.self).subscribe(onNext: { [weak self] (models) in
            
            guard let strongSelf = self else { return }
            let section = CollectionSection.init(items: models)
            strongSelf.vmDatas.value = [section]
            
        }, onError: { [weak self]  (error) in
            
            stopAnimating()
            self?.refreshStatus.value = .endHeaderRefresh
            self?.refreshStatus.value = .endFooterRefresh
            
        }, onCompleted: {  [weak self]  in
            stopAnimating()
            self?.isNull.value = (self?.vmDatas.value.first?.items.count == 0)
            self?.refreshStatus.value = .endHeaderRefresh
            self?.refreshStatus.value = .endFooterRefresh
            
        }).disposed(by: disposeBag)
    }
}


struct CollectionSection {
    var items: [CollectionModel]
}

extension CollectionSection: SectionModelType {
    typealias Item = CollectionModel
    init(original: CollectionSection, items: [CollectionModel]) {
        self = original
        self.items = items
    }
}
